import PageContainer from '@/components/PageContainer';
import useEvent from '@/hooks/useEvent';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import { getDeviceShareLink } from '@/utils/deviceShare';
import { Canvas, Text, View } from '@tarojs/components';
import Taro, { useReady, useRouter } from '@tarojs/taro';
import I18n from 'i18n-js';
import React, { useMemo, useRef } from 'react';
import drawQrcode from 'weapp-qrcode-canvas-2d';

const dstyles = GStyleSheet.create({
  container: {
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  tips: {
    fontSize: 14,
    marginTop: 50,
    padding: '0 20rpx',
  },
  qrCode: {
    marginTop: 20,
    marginBottom: 20,
  },
  expiryTime: {
    fontSize: 16,
    marginBottom: 35,
    paddingRight: 20,
    paddingLeft: 20,
  },
  save: {
    fontSize: 16,
    color: DynamicColors.tintColor,
  }
});

type Params = {
  shareId: string;
  expiryTime: string;
}

const SharedQrCode = React.memo(() => {
  const router = useRouter<Params>();
  const styles = dstyles.useDynamicStyle();
  const tempFilePathRef = useRef<string | null>(null);

  const url = useMemo(() => {
    return getDeviceShareLink(router.params.shareId);
  }, [router.params.shareId]);

  console.log('SharedQrCode url', url)

  const size = useMemo(() => {
    const systemInfo = Taro.getSystemInfoSync();
    return Math.ceil(systemInfo.screenWidth / 375 * 220);
  }, []);

  const canvasStyle = useMemo(() => ({ width: size, height: size }), [size]);

  const drawOfNumberRef = useRef(0);

  const drawUrlQrCode = useEvent(() => {
    const query = Taro.createSelectorQuery()
    query.select('#qrCode')
      .fields({ node: true, size: true })
      .exec((res) => {
        drawOfNumberRef.current += 1;
        if (!res[0]) {
          drawOfNumberRef.current !== 5 && setTimeout(() => drawUrlQrCode(), 100);
          return;
        }
        const canvas = res[0].node;
        drawQrcode({
          canvas,
          canvasId: 'qrCode',
          width: size,
          padding: 30,
          background: '#ffffff',
          foreground: '#000000',
          text: url,
        })

        Taro.canvasToTempFilePath({
          canvasId: 'qrCode',
          canvas: canvas,
          x: 0,
          y: 0,
          width: size,
          height: size,
          destWidth: size,
          destHeight: size,
          success(tempRes) {
            tempFilePathRef.current = tempRes.tempFilePath;
          },
          fail(tempRes) {
            console.error(tempRes)
          }
        })
      })
  })

  useReady(() => {
    drawUrlQrCode();
  })

  const handleClick = useEvent(() => {
    if (!tempFilePathRef.current) {
      return;
    }
    Taro.saveImageToPhotosAlbum({
      filePath: tempFilePathRef.current,
      success: () => {
        Taro.showToast({
          icon: 'success',
          title: '保存成功'
        })
      },
      fail: (error) => {
        // console.log('error', error);
        Taro.showToast({
          icon: 'error',
          title: '保存失败'
        })
      }
    })
  })

  return (
    <PageContainer title={I18n.t('QRCODE_SHARE')}>
      <View style={styles.container}>
        <Text style={styles.tips}>{I18n.t('SHARE_QRCODE_TIPS')}</Text>
        <View style={styles.qrCode}>
          <Canvas type='2d' id='qrCode' canvasId='qrCode' style={canvasStyle} />
        </View>
        <Text style={styles.expiryTime}>本次二维码有效期至 {router.params.expiryTime}</Text>
        <Text style={styles.save} onClick={handleClick}>{I18n.t('SAVE_IMAGE')}</Text>
      </View>
    </PageContainer>
  )
});

export default SharedQrCode;
